const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { logOperation } = require('./logs');

// 状态码定义
const CODE = {
  SUCCESS: 0,
  PARAM_ERROR: 1001,
  NOT_FOUND: 1002,
  SERVER_ERROR: 500,
  NO_PERMISSION: 1003
};

/**
 * 获取Bug列表
 * GET /api/bugs/list
 * 支持按项目、模块筛选和分页
 */
router.get('/lists', async (req, res) => {
  try {
    // 分页参数
    const page = req.query.page || 1,         // 当前页码，默认为第1页
    pageSize = req.query.pageSize || 10,      // 每页显示的记录数，默认为10条
    projectId = req.query.projectId,          // 项目ID，用于按项目过滤缺陷
    moduleId = req.query.moduleId,            // 模块ID，用于按模块过滤缺陷
    title = req.query.title,                  // 缺陷标题关键词，用于模糊搜索
    status = req.query.status,                // 缺陷状态，如：待修复、已解决、已关闭等
    priority = req.query.priority,            // 缺陷优先级，如：低、中、高、紧急
    assigneeId = req.query.assigneeId,        // 分配给谁的缺陷（被指派人的用户ID）
    reporterId = req.query.reporterId,        // 缺陷报告人的用户ID
    startDate = req.query.startDate,          // 缺陷创建的起始日期
    endDate = req.query.endDate,              // 缺陷创建的结束日期
    severity = req.query.severity,            // 缺陷严重程度，如：轻微、一般、严重、致命
    deadline = req.query.deadline;            // 缺陷的处理截止日期

    let conditions = [];
    let params = [];
    let whereClause = '';

    // 构建查询条件
    if (projectId) {
      conditions.push('b.project_id = ?');
      params.push(projectId);
    }
    if (moduleId) {
      conditions.push('b.module_id = ?');
      params.push(moduleId);
    }
    if (title) {
      conditions.push('b.title LIKE ?');
      params.push(`%${title}%`);
    }
    if (status) {
      conditions.push('b.status = ?');
      params.push(status);
    }
    if (priority) {
      conditions.push('b.priority = ?');
      params.push(priority);
    }
    if (assigneeId) {
      conditions.push('b.assignee_id = ?');
      params.push(assigneeId);
    }
    if (reporterId) {
      conditions.push('b.reporter_id = ?');
      params.push(reporterId);
    }
    if (startDate && endDate) {
      conditions.push('b.create_time BETWEEN ? AND ?');
      params.push(startDate, endDate);
    }
    if (severity) {
      conditions.push('b.severity = ?');
      params.push(severity);
    }
    if (deadline) {
      conditions.push('b.deadline = ?');
      params.push(deadline);
    }

    if (conditions.length > 0) {
      whereClause = 'WHERE ' + conditions.join(' AND ');
    }

    // 计算总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM bugs b ${whereClause}`,
      params
    );
    const total = countResult[0].total;

    // 获取分页数据
    const offset = (page - 1) * pageSize;
    const [bugs] = await pool.execute(
      `SELECT b.*, 
        p.name as project_name,
        m.name as module_name,
        u1.username as assignee_name,
        u1.real_name as assignee_real_name,
        u2.username as reporter_name,
        u2.real_name as reporter_real_name
       FROM bugs b
       LEFT JOIN projects p ON b.project_id = p.id
       LEFT JOIN modules m ON b.module_id = m.id
       LEFT JOIN users u1 ON b.assignee_id = u1.id
       LEFT JOIN users u2 ON b.reporter_id = u2.id
       ${whereClause}
       ORDER BY b.priority DESC, b.create_time DESC
       LIMIT ? OFFSET ?`,
      [...params, parseInt(pageSize), offset]
    );

    // 记录操作日志
    await logOperation({
      userId: req.user ? req.user.userId : null,
      type: 'bug_list_query',
      module: '缺陷管理',
      details: JSON.stringify({ page, pageSize, ...req.query }),
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });

    res.json({
      code: CODE.SUCCESS,
      message: '获取Bug列表成功',
      data: {
        total,
        list: bugs,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    console.error('获取Bug列表错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 创建新Bug
 * POST /api/bugs
 */
router.post('/create', async (req, res) => {
  try {
    const {
      title,            // Bug的简短标题或描述
      description,      // Bug的详细描述和重现步骤
      projectId,        // 所属项目ID
      moduleId,         // 所属模块ID
      status,           // Bug状态
      priority,         // Bug优先级
      severity,         // Bug严重程度
      deadline,         // Bug的处理截止日期
      assigneeId,       // 指派给谁
      reporterId,       // 报告人ID
    } = req.body;


    console.log("提交的参数：",req.body);

    // 参数验证
    if (!title) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '缺陷标题不能为空'
      });
    }

    if (!description) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '缺陷描述不能为空'
      });
    }   

    if (!projectId) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '项目ID不能为空'
      });
    }

    if (!reporterId) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '报告人ID不能为空'
      });
    }

    if (!assigneeId) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '处理人ID不能为空'
      });
    }

    if (!deadline) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '处理截止日期不能为空'
      });
    }

    // 检查项目是否存在
    const [projects] = await pool.execute(
      'SELECT id FROM projects WHERE id = ?',
      [projectId]
    );

    if (projects.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '项目不存在'
      });
    }

    // 如果指定了模块，检查模块是否存在
    if (moduleId) {
      const [modules] = await pool.execute(
        'SELECT id FROM modules WHERE id = ? AND project_id = ?',
        [moduleId, projectId]
      );

      if (modules.length === 0) {
        return res.json({
          code: CODE.NOT_FOUND,
          message: '模块不存在或不属于该项目'
        });
      }
    }

    // 检查报告人是否存在
    const [reporters] = await pool.execute(
      'SELECT id FROM users WHERE id = ? AND status = 1',
      [reporterId]
    );

    if (reporters.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '报告人不存在或已被禁用'
      });
    }

    // 如果指定了处理人，检查处理人是否存在
    if (assigneeId) {
      const [assignees] = await pool.execute(
        'SELECT id FROM users WHERE id = ? AND status = 1',
        [assigneeId]
      );

      if (assignees.length === 0) {
        return res.json({
          code: CODE.NOT_FOUND,
          message: '处理人不存在或已被禁用'
        });
      }
    }

    // 插入Bug记录
    const [result] = await pool.execute(
      `INSERT INTO bugs 
      (title, description, project_id, module_id, reporter_id, assignee_id, 
      status,severity,priority, deadline, create_time) 
      VALUES (?, ?, ?,?, ?, ?, ?, ?, ?, ?,NOW())`,
      [
        title, 
        description, 
        projectId, 
        moduleId, 
        reporterId, 
        assigneeId, 
        status || '待评估', 
        severity|| '一般',
        priority || '中等', 
        deadline || null
      ]
    );

    // 记录操作日志
    await logOperation({
      userId: req.user ? req.user.userId : null,
      type: 'bug_create',
      module: '缺陷管理',
      details: JSON.stringify({ id: result.insertId, ...req.body }),
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });

    res.json({
      code: CODE.SUCCESS,
      message: '创建Bug成功',
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error('创建Bug错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取Bug详情
 * GET /api/bugs/:id
 */
router.get('/detail/:id', async (req, res) => {
  try {
    const { id } = req.params;

    // 获取Bug详情，包括关联的项目、模块、用户信息
    const [bugs] = await pool.execute(
      `SELECT 
        b.*, 
        p.name as project_name,
        m.name as module_name,
        u1.username as assignee_name,
        u1.real_name as assignee_real_name,
        u2.username as reporter_name,
        u2.real_name as reporter_real_name,
        (SELECT COUNT(*) FROM bug_comments WHERE bug_id = b.id) as comment_count
       FROM bugs b
       LEFT JOIN projects p ON b.project_id = p.id
       LEFT JOIN modules m ON b.module_id = m.id
       LEFT JOIN users u1 ON b.assignee_id = u1.id
       LEFT JOIN users u2 ON b.reporter_id = u2.id
       WHERE b.id = ?`,
      [id]
    );

    if (bugs.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: 'Bug不存在'
      });
    }

    // 获取Bug的评论列表
    const [comments] = await pool.execute(
      `SELECT 
        bc.*, 
        u.username as commenter_name,
        u.real_name as commenter_real_name
       FROM bug_comments bc
       LEFT JOIN users u ON bc.user_id = u.id
       WHERE bc.bug_id = ?
       ORDER BY bc.created_at DESC`,
      [id]
    );

    // 记录操作日志
    await logOperation({
      userId: req.user ? req.user.userId : null,
      type: 'bug_detail_query',
      module: '缺陷管理',
      details: JSON.stringify({ id }),
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });

    res.json({
      code: CODE.SUCCESS,
      message: '获取Bug详情成功',
      data: {
        bug: bugs[0],
        comments: comments
      }
    });
  } catch (error) {
    console.error('获取Bug详情错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 更新Bug
 * PUT /api/bugs/:id
 */
router.put('/update/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      title,
      description,
      projectId,
      moduleId,
      assigneeId,
      status,
      priority,
      severity,
      deadline
    } = req.body;

    // 检查Bug是否存在
    const [existingBugs] = await pool.execute(
      'SELECT * FROM bugs WHERE id = ?',
      [id]
    );

    if (existingBugs.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: 'Bug不存在'
      });
    }

    // 如果更新了项目，检查项目是否存在
    if (projectId) {
      const [projects] = await pool.execute(
        'SELECT id FROM projects WHERE id = ?',
        [projectId]
      );

      if (projects.length === 0) {
        return res.json({
          code: CODE.NOT_FOUND,
          message: '项目不存在'
        });
      }
    }

    // 如果更新了模块，检查模块是否存在且属于正确的项目
    if (moduleId) {
      const [modules] = await pool.execute(
        'SELECT id FROM modules WHERE id = ? AND project_id = ?',
        [moduleId, projectId || existingBugs[0].project_id]
      );

      if (modules.length === 0) {
        return res.json({
          code: CODE.NOT_FOUND,
          message: '模块不存在或不属于该项目'
        });
      }
    }

    // 如果更新了处理人，检查处理人是否存在
    if (assigneeId) {
      const [assignees] = await pool.execute(
        'SELECT id FROM users WHERE id = ? AND status = 1',
        [assigneeId]
      );

      if (assignees.length === 0) {
        return res.json({
          code: CODE.NOT_FOUND,
          message: '处理人不存在或已被禁用'
        });
      }
    }

    // 构建更新字段
    const updateFields = [];
    const updateParams = [];

    if (title) {
      updateFields.push('title = ?');
      updateParams.push(title);
    }
    if (description !== undefined) {
      updateFields.push('description = ?');
      updateParams.push(description);
    }
    if (projectId) {
      updateFields.push('project_id = ?');
      updateParams.push(projectId);
    }
    if (moduleId) {
      updateFields.push('module_id = ?');
      updateParams.push(moduleId);
    }
    if (assigneeId) {
      updateFields.push('assignee_id = ?');
      updateParams.push(assigneeId);
    }
    if (status) {
      updateFields.push('status = ?');
      updateParams.push(status);
    }
    if (priority) {
      updateFields.push('priority = ?');
      updateParams.push(priority);
    }
    if (severity) {
      updateFields.push('severity = ?');
      updateParams.push(severity);
    }
    if (deadline) {
      updateFields.push('deadline = ?');
      updateParams.push(deadline);
    }

    updateFields.push('update_time = NOW()');
    updateParams.push(id);

    // 执行更新
    await pool.execute(
      `UPDATE bugs SET ${updateFields.join(', ')} WHERE id = ?`,
      updateParams
    );

    // 记录操作日志
    await logOperation({
      userId: req.user ? req.user.userId : null,
      type: 'bug_update',
      module: '缺陷管理',
      details: JSON.stringify({ id, ...req.body }),
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });

    res.json({
      code: CODE.SUCCESS,
      message: '更新Bug成功'
    });
  } catch (error) {
    console.error('更新Bug错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 删除Bug
 * DELETE /api/bugs/:id
 */
router.delete('/delete', async (req, res) => {
  try {
    const { id } = req.query;

    if (!id) {
      return res.json({
        code: CODE.BAD_REQUEST,
        message: '缺少必要参数'
      });
    }

    // 检查Bug是否存在
    const [existingBugs] = await pool.execute(
      'SELECT * FROM bugs WHERE id = ?',
      [id]
    );

    if (existingBugs.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: 'Bug不存在'
      });
    }

    // 执行删除
    await pool.execute(
      'DELETE FROM bugs WHERE id = ?',
      [id]
    );

    // 删除关联的评论
    await pool.execute(
      'DELETE FROM bug_comments WHERE bug_id = ?',
      [id]
    );

    // 记录操作日志
    await logOperation({
      userId: req.user ? req.user.userId : null,
      type: 'bug_delete',
      module: '缺陷管理',
      details: JSON.stringify({ id }),
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });

    res.json({
      code: CODE.SUCCESS,
      message: '删除Bug成功'
    });
  } catch (error) {
    console.error('删除Bug错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 添加Bug评论
 * POST /api/bugs/:id/comments
 */
router.post('/:id/comments', async (req, res) => {
  try {
    const { id } = req.params;
    const { userId, content } = req.body;

    // 检查Bug是否存在
    const [existingBugs] = await pool.execute(
      'SELECT * FROM bugs WHERE id = ?',
      [id]
    );

    if (existingBugs.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: 'Bug不存在'
      });
    }

    // 检查用户是否存在
    const [users] = await pool.execute(
      'SELECT * FROM users WHERE id = ? AND status = 1',
      [userId]
    );

    if (users.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '用户不存在或已被禁用'
      });
    }

    // 插入评论
    const [result] = await pool.execute(
      `INSERT INTO bug_comments 
        (bug_id, user_id, content, create_time) 
      VALUES 
        (?, ?, ?, NOW())`,
      [id, userId, content]
    );

    // 记录操作日志
    await logOperation({
      userId: req.user ? req.user.userId : null,
      type: 'bug_comment_create',
      module: '缺陷管理',
      details: JSON.stringify({ id, commentId: result.insertId, ...req.body }),
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });

    res.json({
      code: CODE.SUCCESS,
      message: '添加Bug评论成功',
      data: { commentId: result.insertId }
    });
  } catch (error) {
    console.error('添加Bug评论错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取Bug统计信息
 * GET /api/bugs/statistics
 */
router.get('/statistics', async (req, res) => {
  try {
    const { projectId, moduleId } = req.query;

    let conditions = [];
    let params = [];

    if (projectId) {
      conditions.push('project_id = ?');
      params.push(projectId);
    }

    if (moduleId) {
      conditions.push('module_id = ?');
      params.push(moduleId);
    }

    const whereClause = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';

    // 获取Bug状态统计
    const [statusStats] = await pool.execute(
      `SELECT 
        status, 
        COUNT(*) as count,
        ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM bugs ${whereClause}), 2) as percentage
      FROM bugs
      ${whereClause}
      GROUP BY status`,
      params
    );

    // 获取Bug优先级统计
    const [priorityStats] = await pool.execute(
      `SELECT 
        priority, 
        COUNT(*) as count,
        ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM bugs ${whereClause}), 2) as percentage
      FROM bugs
      ${whereClause}
      GROUP BY priority`,
      params
    );

    // 获取Bug严重程度统计
    const [severityStats] = await pool.execute(
      `SELECT 
        severity, 
        COUNT(*) as count,
        ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM bugs ${whereClause}), 2) as percentage
      FROM bugs
      ${whereClause}
      GROUP BY severity`,
      params
    );

    // 记录操作日志
    await logOperation({
      userId: req.user ? req.user.userId : null,
      type: 'bug_statistics_query',
      module: '缺陷管理',
      details: JSON.stringify({ projectId, moduleId }),
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });

    res.json({
      code: CODE.SUCCESS,
      message: '获取Bug统计信息成功',
      data: {
        statusStats,
        priorityStats,
        severityStats
      }
    });
  } catch (error) {
    console.error('获取Bug统计信息错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

module.exports = router;
